//
//  SpotSupportValueView.swift
//  swiftProject
//
//  Created by ZhangSai on 2021/7/1.
//

import UIKit



class SpotSupportValueView: UIView ,UITextFieldDelegate{
    var orderInfoModel:OrderListModel!
    var insuredCw:String = ""
    var minimumAmount:String = ""
    var maximumAmount:String = ""

    typealias SpotSupportValueBlock = () -> Void
    var supportValueBlock : SpotSupportValueBlock!

    func setOrderInfoModel(orderInfoModel:OrderListModel) {
        self.orderInfoModel = orderInfoModel
        self.textField.text = orderInfoModel.insureAmount;
        self.detailUnitLab.text = "MMK--" + String(orderInfoModel.insureFreight)
    }
  
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = UIColor.init(red: 0, green: 0, blue: 0, alpha: 0.5)
        self.setUI()
        self.getData()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setUI()  {
        self.addSubview(self.mainView)
        self.mainView.addSubview(self.cencelBtn)
        self.mainView.addSubview(self.titleLab)
        self.mainView.addSubview(self.textField)
        self.mainView.addSubview(self.unitLab)
        self.mainView.addSubview(self.lineView)
        self.mainView.addSubview(self.detailLab)
        self.mainView.addSubview(self.detailUnitLab)
        self.mainView.addSubview(self.explainLab)
        self.mainView.addSubview(self.textView)
        self.mainView.addSubview(self.confirmBtn)

        self.mainView.snp.makeConstraints { (make) in
            make.left.equalTo(self.snp.left).offset(0)
            make.right.equalTo(self.snp.right).offset(0)
            make.bottom.equalTo(self.snp.bottom).offset(15)
            make.top.equalTo(self.snp.top).offset(140)
        }
        self.cencelBtn.snp.makeConstraints { (make) in
            make.height.equalTo(40)
            make.width.equalTo(40)
            make.top.equalTo(self.mainView.snp.top).offset(15)
            make.right.equalTo(self.snp.top).offset(-15)
        }
        self.titleLab.snp.makeConstraints { (make) in
            make.left.equalTo(self.mainView.snp.left).offset(15)
            make.top.equalTo(self.mainView.snp.top).offset(15)
        }
        self.lineView.snp.makeConstraints { (make) in
            make.left.equalTo(self.mainView.snp.left).offset(20)
            make.right.equalTo(self.mainView.snp.right).offset(-40)
            make.top.equalTo(self.titleLab.snp.bottom).offset(60)
            make.height.equalTo(1)
        }
        self.unitLab.snp.makeConstraints { (make) in
            make.right.equalTo(self.snp.right).offset(-20)
            make.top.equalTo(self.titleLab.snp.bottom).offset(0)
            make.bottom.equalTo(self.lineView.snp.top).offset(0)
            make.width.equalTo(80)
        }
        self.textField.snp.makeConstraints { (make) in
            make.left.equalTo(self.mainView.snp.left).offset(20)
            make.top.equalTo(self.titleLab.snp.bottom).offset(5)
            make.right.equalTo(self.unitLab.snp.left).offset(-15)
            make.bottom.equalTo(self.lineView.snp.top).offset(0);
        }
        self.detailUnitLab.snp.makeConstraints { (make) in
            make.right.equalTo(self.snp.right).offset(-40);
            make.top.equalTo(self.lineView.snp.bottom).offset(20);
            make.height.equalTo(20);
        }
        self.detailLab.snp.makeConstraints { (make) in
            make.right.equalTo(self.detailUnitLab.snp.left).offset(-10);
            make.centerY.equalTo(self.detailUnitLab.snp.centerY);
        }
        self.explainLab.snp.makeConstraints { (make) in
            make.left.equalTo(self.mainView.snp.left).offset(15);
            make.top.equalTo(self.detailUnitLab.snp.bottom).offset(10);
        }
        self.confirmBtn.snp.makeConstraints { (make) in
            make.left.equalTo(self.mainView.snp.left).offset(60);
            make.right.equalTo(self.mainView.snp.right).offset(-60);
            make.bottom.equalTo(self.mainView.snp.bottom).offset(-(Constants.xSafeBottomHeight == 0 ? 23 : Constants.xSafeBottomHeight + 23));
            make.height.equalTo(40);
        }
        self.textView.snp.makeConstraints { (make) in
            make.left.equalTo(self.mainView.snp.left).offset(15);
            make.top.equalTo(self.explainLab.snp.bottom).offset(10);
            make.right.equalTo(self.mainView.snp.right).offset(-15);
            make.bottom.equalTo(self.confirmBtn.snp.top).offset(-10);
        }
        self.setValueUI()
    }
    
    func getData()  {
        if self.insuredCw.count <= 0 {
            Constants.window?.makeToastActivity(.center)
            HttpService.sharedHttpService().getInsuredPlanSuccess { (json, state, error) in
                Constants.window?.hideAllToasts()
                Constants.window?.hideAllToasts()
                if !state {
                    self.maximumAmount = "1000000"
                    self.minimumAmount = "200000"
                    Constants.window?.makeToast(error)
                    return;
                }
                let aryData:Dictionary = json["data"].dictionary ?? Dictionary()
                self.insuredCw = aryData["insuredCw"]?.description ?? ""
                self.maximumAmount = String(aryData["maximumAmount"]?.description ?? "")
                self.minimumAmount = String(aryData["minimumAmount"]?.description ?? "")
                if self.maximumAmount.count <= 0 || self.minimumAmount.count <= 0 {
                    self.maximumAmount = "1000000"
                    self.minimumAmount = "200000"
                }
                let str = UserDefaults.standard.string(forKey:LanguageHeader.MySystemLanguage)
                var hintStr:String = ""
                if (str == LanguageHeader.ChinaLanguage) {
                    hintStr = self.minimumAmount + "-" + self.maximumAmount + ZslanguageTool.sharedLanguageTool().getIanguageWithKey(key: LanguageHeader.order_hint_integer)
                } else if (str == LanguageHeader.BurmaLanguage) {
                    hintStr = self.minimumAmount + "-" + self.maximumAmount + ZslanguageTool.sharedLanguageTool().getIanguageWithKey(key: LanguageHeader.order_hint_integer)
                } else {
                    hintStr = "Integers from" + self.minimumAmount + "to" +  self.maximumAmount
                }
                self.textField.placeholder = hintStr
                if self.insuredCw.count > 0 {
                    let paragraphStyle = NSMutableParagraphStyle.init()
                    if (str == LanguageHeader.BurmaLanguage) {
                        paragraphStyle.lineSpacing = 6
                    } else {
                        paragraphStyle.lineSpacing = 4
                    }
                    let text = NSAttributedString.init(string: self.insuredCw, attributes: [NSAttributedString.Key.font:UIFont.systemFont(ofSize: 17),NSAttributedString.Key.paragraphStyle:paragraphStyle])
                    self.textView.attributedText = text
                }
                self.detailUnitLab.text = "MMK--" + String(self.orderInfoModel.insureFreight)
            }
        }
    }
    
    func setValueUI() {
        self.titleLab.text = ZslanguageTool.sharedLanguageTool().getIanguageWithKey(key: LanguageHeader.WL_spot_support_Value)
        self.textField.text = orderInfoModel.insureAmount
        self.detailLab.text = ZslanguageTool.sharedLanguageTool().getIanguageWithKey(key: LanguageHeader.WL_spot_support_cost)
        self.explainLab.text = ZslanguageTool.sharedLanguageTool().getIanguageWithKey(key: LanguageHeader.WL_spot_support_explain)
        self.confirmBtn.setTitle(ZslanguageTool.sharedLanguageTool().getIanguageWithKey(key: LanguageHeader.WL_spot_support_affirm), for: .normal)
    }
    
    @objc func clickCancelBtn() {
        self.removeFromSuperview()
    }
    
    @objc func clickConfirmBtn()  {
        if self.textField.text?.count ?? 0 <= 0 {
            self.orderInfoModel.insureAmount = ""
            self.orderInfoModel.insureFreight = 0
            self.orderInfoModel.isInsure = 0
            if (self.supportValueBlock != nil) {
                self.supportValueBlock()
            }
            self.removeFromSuperview()
            return
        }
        if self.textField.text ?? "" > self.maximumAmount || self.textField.text ?? ""  < self.minimumAmount {
            var str:NSString = ZslanguageTool.sharedLanguageTool().getIanguageWithKey(key: LanguageHeader.order_import_integer) as NSString
            str = str.replacingOccurrences(of: "minimumAmount", with: self.minimumAmount) as NSString
            str = str.replacingOccurrences(of: "maximumAmount", with: self.maximumAmount) as NSString
            Constants.window?.makeToast(str as String)
            return
        }
        if self.confirmBtn.isSelected {
            let dicData:Dictionary = ["insureAmount":self.textField.text]
            HttpService.sharedHttpService().getCalculateInsuredFreight(dicData: dicData as Dictionary<String, Any>) { (json, state, error) in
                if state {
                    let jsonData:Dictionary = json["data"].dictionary ?? Dictionary()
                    self.orderInfoModel.insureAmount = self.textField.text ?? ""
                    self.orderInfoModel.insureFreight = jsonData["insuranceCost"]?.double ?? 0
                    self.orderInfoModel.isInsure = 1
                    if (self.supportValueBlock != nil) {
                        self.supportValueBlock();
                    }
                    self.removeFromSuperview()
                } else {
                    Constants.window?.hideAllToasts()
                    Constants.window?.hideToastActivity()
                    Constants.window?.makeToast(error)
                }
            }
        }
    }

    @objc func textFieldChange() {
        self.confirmBtn.backgroundColor = UIColor.init(hexString: "#FFD10A")
        self.confirmBtn.setTitleColor(UIColor.init(hexString: "#000000"), for: .normal)
        self.confirmBtn.isSelected = true
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesBegan(touches, with: event)
        self.endEditing(true)
    }
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let cs:CharacterSet = CharacterSet.init(charactersIn: "0123456789.").inverted
        let filtered = string.components(separatedBy: cs).joined(separator: "")
        if string != filtered {
            return false
        }
        if string == "" {
            self.perform(#selector(textFieldChange), with: self, afterDelay: 0.3)
            return true
        }
        
        if (textField.text! as NSString).range(of: ".").location != NSNotFound {
            if string == "." {
                return false
            }
        } else {
            if textField.text?.count ?? 0 > 0 {
                if textField.text?.prefix(1) == "0" {
                    if string != "." {
                        return false
                    }
                }
            } else {
                if string == "." {
                    return false
                }
            }
        }
        let totalStr = textField.text ?? "" + string
        if totalStr > self.maximumAmount {
            var str:NSString = ZslanguageTool.sharedLanguageTool().getIanguageWithKey(key: LanguageHeader.order_import_integer) as NSString
            str = str.replacingOccurrences(of: "minimumAmount", with: self.minimumAmount) as NSString
            str = str.replacingOccurrences(of: "maximumAmount", with: self.maximumAmount) as NSString
            Constants.window?.makeToast(str as String)
            return false
        }
        self.perform(#selector(textFieldChange), with: self, afterDelay: 0.3)
        return true
    }
    
    lazy var mainView: UIView = {
        let mainView = UIView()
        mainView.backgroundColor = UIColor.white
        mainView.layer.masksToBounds = true
        mainView.layer.cornerRadius = 15
        return mainView
    }()
    
    lazy var titleLab: UILabel = {
        let titleLab = UILabel()
        titleLab.font = UIFont.systemFont(ofSize: 17)
        titleLab.textColor = UIColor.init(hexString: "#4C4C4C")
        return titleLab
    }()
    lazy var unitLab: UILabel = {
        let unitLab = UILabel()
        unitLab.font = UIFont.systemFont(ofSize: 17)
        unitLab.textColor = UIColor.init(hexString: "#000000")
        unitLab.text = "(MMK)"
        return unitLab
    }()
    lazy var textField: UITextField = {
        let textField = UITextField()
        textField.font = UIFont.systemFont(ofSize: 17)
        textField.textColor = UIColor.init(hexString: "#000000")
        textField.delegate = self
        textField.keyboardType = UIKeyboardType.numberPad
        return textField
    }()
    lazy var detailLab: UILabel = {
        let detailLab = UILabel()
        detailLab.font = UIFont.systemFont(ofSize: 12)
        detailLab.textColor = UIColor.init(hexString: "#000000")
        return detailLab
    }()
    lazy var detailUnitLab: UILabel = {
        let detailUnitLab = UILabel()
        detailUnitLab.font = UIFont.systemFont(ofSize: 12)
        detailUnitLab.textColor = UIColor.init(hexString: "#B20000")
        return detailUnitLab
    }()
    lazy var explainLab: UILabel = {
        let explainLab = UILabel()
        explainLab.font = UIFont.systemFont(ofSize: 15)
        explainLab.textColor = UIColor.init(hexString: "#000000")
        return explainLab
    }()
    lazy var textView:UITextView = {
        let textView = UITextView()
        textView.font = UIFont.systemFont(ofSize: 15)
        textView.textColor = UIColor.init(hexString: "#3A3A3A")
        textView.isEditable = false
        return textView
    }()
    lazy var lineView: UIView = {
        let lineView = UIView()
        lineView.backgroundColor = UIColor.init(hexString: "#CACACA")
        return lineView
    }()
    lazy var confirmBtn: UIButton = {
        let confirmBtn = UIButton.init(type: .custom)
        confirmBtn.addTarget(self, action: #selector(clickConfirmBtn), for: .touchUpInside)
        confirmBtn.layer.masksToBounds = true
        confirmBtn.layer.cornerRadius = 20
        confirmBtn.titleLabel?.font = UIFont.boldSystemFont(ofSize: 17)
        confirmBtn.backgroundColor = UIColor.init(hexString: "#FFD10A")
        confirmBtn.setTitleColor(UIColor.init(hexString: "#000000"), for: .normal)
        confirmBtn.isSelected = true
        return confirmBtn
    }()
    lazy var cencelBtn: UIButton = {
        let cencelBtn = UIButton.init(type: .custom)
        cencelBtn.setImage(UIImage.init(named: "login_cancel"), for: .normal)
        cencelBtn.addTarget(self, action: #selector(clickCancelBtn), for: .touchUpInside)
        return cencelBtn
    }()
}
